<template>
  <div class="article-detail-container">
    <div class="article-container" v-loading="loading">
      <!-- 文章内容 -->
      <div v-if="article" class="article-content">
        <h1 class="article-title">{{ article.title }}</h1>
        
        <div class="article-meta">
          <div class="meta-left">
            <span class="author"><i class="el-icon-user"></i> {{ article.author }}</span>
            <span class="date"><i class="el-icon-date"></i> {{ formatDate(article.publishDate) }}</span>
            <span class="category" v-if="article.categoryName">
              <i class="el-icon-collection-tag"></i> {{ article.categoryName }}
            </span>
          </div>
          <div class="meta-right">
            <span class="views"><i class="el-icon-view"></i> {{ article.views }}</span>
            <span class="likes" :class="{ 'liked': isLiked }" @click="toggleLike">
              <i :class="isLiked ? 'el-icon-star-on' : 'el-icon-star-off'"></i> {{ article.likes }}
            </span>
          </div>
        </div>

        <div class="article-cover" v-if="article.coverImg">
          <img :src="article.coverImg" :alt="article.title">
        </div>

        <div class="article-body" v-html="article.content"></div>
        
        <!-- 文章标签 -->
        <div class="article-tags" v-if="article.tags && article.tags.length > 0">
          <span class="tag-label"><i class="el-icon-price-tag"></i> 标签：</span>
          <el-tag v-for="tag in article.tags" :key="tag.id" size="small" effect="plain" type="danger">{{ tag.name }}</el-tag>
        </div>
      </div>

      <!-- 相关文章 -->
      <div v-if="relatedArticles.length > 0" class="related-articles">
        <h3 class="section-title">相关文章</h3>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" v-for="item in relatedArticles" :key="item.id">
            <div class="related-article-card" @click="viewArticle(item.id)">
              <div class="related-img">
                <img :src="item.coverImg || '/images/default-article.jpg'" :alt="item.title">
              </div>
              <div class="related-info">
                <h4 class="related-title">{{ item.title }}</h4>
                <p class="related-summary">{{ item.summary }}</p>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <div class="comment-section">
        <h3 class="section-title">评论区 ({{ totalComments }})</h3>
        
        <!-- 评论表单 -->
        <div class="comment-form">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="分享你的看法..."
            v-model="commentContent"
            maxlength="500"
            show-word-limit
          ></el-input>
          <div class="form-actions">
            <el-button type="primary" :disabled="!commentContent.trim()" @click="submitComment">发表评论</el-button>
          </div>
        </div>

        <!-- 评论列表 -->
        <div v-if="comments.length > 0" class="comment-list">
          <div v-for="comment in comments" :key="comment.id" class="comment-item">
            <div class="comment-avatar">
              <img :src="comment.avatar || '/images/default-avatar.png'" :alt="comment.userName">
            </div>
            <div class="comment-content">
              <div class="comment-header">
                <span class="comment-author">{{ comment.userName }}</span>
                <span class="comment-date">{{ formatDate(comment.createTime) }}</span>
              </div>
              <div class="comment-text">{{ comment.content }}</div>
              <div class="comment-actions">
                <span class="comment-like" :class="{ 'liked': comment.isLiked }" @click="toggleCommentLike(comment)">
                  <i :class="comment.isLiked ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
                  <span>{{ comment.likes || 0 }}</span>
                </span>
                <span class="comment-reply" @click="replyToComment(comment)">
                  <i class="el-icon-chat-dot-round"></i> 回复
                </span>
              </div>

              <!-- 回复区域 -->
              <div v-if="replyingTo === comment.id" class="reply-form">
                <el-input
                  type="textarea"
                  :rows="3"
                  :placeholder="`回复 ${comment.userName}...`"
                  v-model="replyContent"
                  maxlength="300"
                  show-word-limit
                ></el-input>
                <div class="form-actions">
                  <el-button size="small" @click="cancelReply">取消</el-button>
                  <el-button size="small" type="primary" :disabled="!replyContent.trim()" @click="submitReply(comment)">回复</el-button>
                </div>
              </div>

              <!-- 子评论 -->
              <div v-if="comment.replies && comment.replies.length > 0" class="comment-replies">
                <div v-for="reply in comment.replies" :key="reply.id" class="reply-item">
                  <div class="reply-avatar">
                    <img :src="reply.avatar || '/images/default-avatar.png'" :alt="reply.userName">
                  </div>
                  <div class="reply-content">
                    <div class="reply-header">
                      <span class="reply-author">{{ reply.userName }}</span>
                      <span class="reply-target" v-if="reply.replyToUserName">回复 {{ reply.replyToUserName }}</span>
                      <span class="reply-date">{{ formatDate(reply.createTime) }}</span>
                    </div>
                    <div class="reply-text">{{ reply.content }}</div>
                    <div class="reply-actions">
                      <span class="reply-like" :class="{ 'liked': reply.isLiked }" @click="toggleReplyLike(reply)">
                        <i :class="reply.isLiked ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
                        <span>{{ reply.likes || 0 }}</span>
                      </span>
                      <span class="reply-reply" @click="replyToReply(comment, reply)">
                        <i class="el-icon-chat-dot-round"></i> 回复
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 暂无评论 -->
        <div v-else-if="!loading" class="no-comments">
          <i class="el-icon-chat-dot-square"></i>
          <p>暂无评论，快来发表第一条评论吧！</p>
        </div>

        <!-- 评论分页 -->
        <div v-if="totalComments > 0" class="comment-pagination">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="totalComments"
            :page-size="commentPageSize"
            :current-page.sync="commentPage"
            @current-change="handleCommentPageChange">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import service from '@/utils/request'

export default {
  name: 'ArticleDetailVue',
  data() {
    return {
      loading: true,
      articleId: null,
      article: null,
      isLiked: false,
      relatedArticles: [],
      
      // 评论相关
      comments: [],
      totalComments: 0,
      commentPage: 1,
      commentPageSize: 10,
      commentContent: '',
      replyingTo: null,
      replyToUserId: null,
      replyContent: ''
    }
  },
  created() {
    this.articleId = this.$route.params.id
    this.getArticleDetail()
    this.checkIfLiked()
    this.getComments()
  },
  methods: {
    // 获取文章详情
    getArticleDetail() {
      this.loading = true
      service.get(`/api/education/article/${this.articleId}`).then(res => {
        this.loading = false
        if (res.code === 200 && res.data) {
          this.article = res.data
          document.title = `${this.article.title} - 京剧苑`
          
          // 获取相关文章
          this.getRelatedArticles()
        } else {
          this.$message.error('文章不存在或已被删除')
          this.$router.push('/education')
        }
      }).catch(err => {
        this.loading = false
        console.error('获取文章详情失败:', err)
        this.$message.error('获取文章详情失败，请稍后重试')
      })
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '未知日期'
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
    },
    
    // 获取相关文章
    getRelatedArticles() {
      if (!this.article || !this.article.id) return
      
      service.get(`/api/education/article/related/${this.article.id}`).then(res => {
        if (res.code === 200 && res.data) {
          this.relatedArticles = res.data.slice(0, 3) // 最多显示3篇相关文章
        }
      }).catch(err => {
        console.error('获取相关文章失败:', err)
      })
    },
    
    // 查看相关文章
    viewArticle(id) {
      if (id === this.articleId) return
      this.$router.push(`/education/article/${id}`)
      // 刷新当前页面
      this.articleId = id
      this.getArticleDetail()
      this.checkIfLiked()
      this.getComments()
      window.scrollTo(0, 0)
    },
    
    // 检查是否已点赞
    checkIfLiked() {
      const token = localStorage.getItem('token')
      if (!token) return
      
      service.get(`/api/education/article/liked/${this.articleId}`).then(res => {
        if (res.code === 200) {
          this.isLiked = res.data
        }
      }).catch(err => {
        console.error('检查点赞状态失败:', err)
      })
    },
    
    // 切换点赞状态
    toggleLike() {
      // 检查登录状态
      const token = localStorage.getItem('token')
      if (!token) {
        this.$message.warning('请先登录后再点赞')
        return
      }
      
      const action = this.isLiked ? 'unlike' : 'like'
      service.post(`/api/education/article/${action}/${this.articleId}`).then(res => {
        if (res.code === 200) {
          this.isLiked = !this.isLiked
          // 更新点赞数
          if (this.isLiked) {
            this.article.likes++
          } else {
            this.article.likes--
          }
          this.$message.success(this.isLiked ? '点赞成功' : '取消点赞成功')
        }
      }).catch(err => {
        console.error('操作点赞失败:', err)
        this.$message.error('操作失败，请稍后重试')
      })
    },
    
    // 获取评论
    getComments() {
      service.get(`/api/education/article/comments/${this.articleId}`, {
        params: {
          page: this.commentPage,
          pageSize: this.commentPageSize
        }
      }).then(res => {
        if (res.code === 200 && res.data) {
          this.comments = res.data.list || []
          this.totalComments = res.data.total || 0
        }
      }).catch(err => {
        console.error('获取评论失败:', err)
        this.$message.error('获取评论失败，请稍后重试')
      })
    },
    
    // 评论分页
    handleCommentPageChange(page) {
      this.commentPage = page
      this.getComments()
    },
    
    // 提交评论
    submitComment() {
      // 检查登录状态
      const token = localStorage.getItem('token')
      if (!token) {
        this.$message.warning('请先登录后再评论')
        return
      }
      
      if (!this.commentContent.trim()) {
        this.$message.warning('评论内容不能为空')
        return
      }
      
      const comment = {
        articleId: this.articleId,
        content: this.commentContent.trim()
      }
      
      service.post('/api/education/article/comment', comment).then(res => {
        if (res.code === 200) {
          this.$message.success('评论成功')
          this.commentContent = ''
          // 重新加载评论
          this.commentPage = 1
          this.getComments()
        }
      }).catch(err => {
        console.error('提交评论失败:', err)
        this.$message.error('评论失败，请稍后重试')
      })
    },
    
    // 点赞评论
    toggleCommentLike(comment) {
      // 检查登录状态
      const token = localStorage.getItem('token')
      if (!token) {
        this.$message.warning('请先登录后再点赞')
        return
      }
      
      const action = comment.isLiked ? 'unlike' : 'like'
      service.post(`/api/education/comment/${action}/${comment.id}`).then(res => {
        if (res.code === 200) {
          comment.isLiked = !comment.isLiked
          // 更新点赞数
          if (comment.isLiked) {
            comment.likes = (comment.likes || 0) + 1
          } else {
            comment.likes = Math.max(0, (comment.likes || 0) - 1)
          }
        }
      }).catch(err => {
        console.error('操作评论点赞失败:', err)
        this.$message.error('操作失败，请稍后重试')
      })
    },
    
    // 点赞回复
    toggleReplyLike(reply) {
      // 检查登录状态
      const token = localStorage.getItem('token')
      if (!token) {
        this.$message.warning('请先登录后再点赞')
        return
      }
      
      const action = reply.isLiked ? 'unlike' : 'like'
      service.post(`/api/education/reply/${action}/${reply.id}`).then(res => {
        if (res.code === 200) {
          reply.isLiked = !reply.isLiked
          // 更新点赞数
          if (reply.isLiked) {
            reply.likes = (reply.likes || 0) + 1
          } else {
            reply.likes = Math.max(0, (reply.likes || 0) - 1)
          }
        }
      }).catch(err => {
        console.error('操作回复点赞失败:', err)
        this.$message.error('操作失败，请稍后重试')
      })
    },
    
    // 回复评论
    replyToComment(comment) {
      // 检查登录状态
      const token = localStorage.getItem('token')
      if (!token) {
        this.$message.warning('请先登录后再回复')
        return
      }
      
      this.replyingTo = comment.id
      this.replyToUserId = comment.userId
      this.replyContent = ''
    },
    
    // 回复回复
    replyToReply(parentComment, reply) {
      // 检查登录状态
      const token = localStorage.getItem('token')
      if (!token) {
        this.$message.warning('请先登录后再回复')
        return
      }
      
      this.replyingTo = parentComment.id
      this.replyToUserId = reply.userId
      this.replyContent = ''
    },
    
    // 取消回复
    cancelReply() {
      this.replyingTo = null
      this.replyToUserId = null
      this.replyContent = ''
    },
    
    // 提交回复
    submitReply(parentComment) {
      if (!this.replyContent.trim()) {
        this.$message.warning('回复内容不能为空')
        return
      }
      
      const reply = {
        commentId: parentComment.id,
        content: this.replyContent.trim(),
        replyToUserId: this.replyToUserId
      }
      
      service.post('/api/education/comment/reply', reply).then(res => {
        if (res.code === 200) {
          this.$message.success('回复成功')
          this.cancelReply()
          // 重新加载评论
          this.getComments()
        }
      }).catch(err => {
        console.error('提交回复失败:', err)
        this.$message.error('回复失败，请稍后重试')
      })
    }
  }
}
</script>

<style scoped>
.article-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  padding-top: 80px;
}

.article-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.article-title {
  font-size: 2.2rem;
  color: #8B0000;
  margin-top: 0;
  margin-bottom: 20px;
  font-family: 'STXingkai', 'STZhongsong', serif;
  text-align: center;
}

.article-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.meta-left, .meta-right {
  display: flex;
  gap: 15px;
}

.article-meta span {
  color: #666;
  font-size: 0.9rem;
  display: flex;
  align-items: center;
}

.article-meta i {
  margin-right: 5px;
}

.likes {
  cursor: pointer;
  transition: all 0.3s ease;
}

.likes:hover {
  color: #FFD700;
}

.likes.liked {
  color: #FFD700;
}

.article-cover {
  margin: 20px 0;
  text-align: center;
}

.article-cover img {
  max-width: 100%;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.article-body {
  line-height: 1.8;
  color: #333;
  margin-bottom: 30px;
}

.article-body img {
  max-width: 100%;
  height: auto;
}

.article-tags {
  margin: 30px 0;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px;
}

.tag-label {
  color: #666;
  font-size: 0.9rem;
  margin-right: 5px;
}

/* 相关文章样式 */
.related-articles {
  margin-top: 40px;
  border-top: 1px dashed #ddd;
  padding-top: 20px;
}

.section-title {
  color: #8B0000;
  font-size: 1.5rem;
  margin-bottom: 20px;
  font-weight: bold;
  position: relative;
  padding-left: 15px;
}

.section-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 5px;
  height: 20px;
  background-color: #8B0000;
  border-radius: 2px;
}

.related-article-card {
  display: flex;
  padding: 15px;
  border-radius: 8px;
  background-color: #f9f9f9;
  gap: 15px;
  cursor: pointer;
  transition: all 0.3s ease;
  height: 100%;
}

.related-article-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 15px rgba(0,0,0,0.1);
}

.related-img {
  width: 100px;
  height: 70px;
  flex-shrink: 0;
  border-radius: 4px;
  overflow: hidden;
}

.related-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.related-info {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.related-title {
  font-size: 1rem;
  color: #333;
  margin: 0 0 8px 0;
  transition: color 0.3s ease;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.related-article-card:hover .related-title {
  color: #8B0000;
}

.related-summary {
  font-size: 0.8rem;
  color: #666;
  margin: 0;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 评论区样式 */
.comment-section {
  margin-top: 40px;
  border-top: 1px dashed #ddd;
  padding-top: 20px;
}

.comment-form {
  margin-bottom: 30px;
}

.form-actions {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.comment-list {
  margin-top: 20px;
}

.comment-item {
  display: flex;
  padding: 20px 0;
  border-bottom: 1px solid #eee;
}

.comment-avatar, .reply-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
  margin-right: 15px;
}

.reply-avatar {
  width: 40px;
  height: 40px;
}

.comment-avatar img, .reply-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.comment-content, .reply-content {
  flex-grow: 1;
}

.comment-header, .reply-header {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.comment-author, .reply-author {
  font-weight: bold;
  color: #333;
}

.reply-target {
  color: #8B0000;
  font-weight: 500;
}

.comment-date, .reply-date {
  color: #999;
  font-size: 0.8rem;
}

.comment-text, .reply-text {
  line-height: 1.6;
  color: #333;
  margin-bottom: 10px;
  word-break: break-word;
}

.comment-actions, .reply-actions {
  display: flex;
  gap: 15px;
}

.comment-like, .comment-reply, .reply-like, .reply-reply {
  color: #999;
  font-size: 0.9rem;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.comment-like i, .reply-like i {
  margin-right: 5px;
}

.comment-like.liked, .reply-like.liked {
  color: #FFD700;
}

.comment-like:hover, .comment-reply:hover,
.reply-like:hover, .reply-reply:hover {
  color: #8B0000;
}

.reply-form {
  margin: 15px 0;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.comment-replies {
  margin-top: 15px;
  padding-left: 20px;
  border-left: 2px solid #eee;
}

.reply-item {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px dashed #eee;
}

.reply-item:last-child {
  border-bottom: none;
}

.no-comments {
  text-align: center;
  padding: 30px;
  color: #999;
}

.no-comments i {
  font-size: 3rem;
  margin-bottom: 10px;
}

.comment-pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .article-detail-container {
    padding: 10px;
    padding-top: 70px;
  }
  
  .article-container {
    padding: 20px;
  }
  
  .article-title {
    font-size: 1.8rem;
  }
  
  .meta-left, .meta-right {
    gap: 10px;
  }
  
  .related-img {
    width: 80px;
    height: 60px;
  }
  
  .related-title {
    font-size: 0.9rem;
  }
  
  .section-title {
    font-size: 1.3rem;
  }
}

@media (max-width: 480px) {
  .article-container {
    padding: 15px;
  }
  
  .article-title {
    font-size: 1.5rem;
  }
  
  .article-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .meta-right {
    width: 100%;
    justify-content: flex-start;
  }
  
  .comment-avatar {
    width: 40px;
    height: 40px;
  }
  
  .reply-avatar {
    width: 30px;
    height: 30px;
  }
  
  .comment-replies {
    padding-left: 10px;
  }
}
</style> 